package com.sso.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sso.entity.Maps;
import com.sso.entity.MapsRes;
import com.sso.entity.Report;
import com.sso.entity.Task;
import com.sso.mapper.SampleMapper;
import com.sso.service.*;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.List;
import java.util.concurrent.Callable;

@Service
public class ThreadUtil implements Callable<Void> {

    private static final Logger logger = LoggerFactory.getLogger(ThreadUtil.class);

    private Process process;
    private String pyPath;
    private Integer scale;
    private String path;
    private Integer taskId;
    private TaskService taskService;

    private MyProperty myProperty;

    private SampleService sampleService;

    private MapsService mapsService;

    private MapsResService mapsResService;

    private ReportService reportService;



    public void initialize(Integer taskId, String pyPath, Integer scale, String path) {
        this.pyPath = pyPath;
        this.scale = scale;
        this.path = path;
        this.taskId = taskId;

        ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();
        taskService = applicationContext.getBean(TaskService.class);
        mapsResService=applicationContext.getBean(MapsResService.class);
        mapsService=applicationContext.getBean(MapsService.class);
        sampleService=applicationContext.getBean(SampleService.class);
        myProperty=applicationContext.getBean(MyProperty.class);
        reportService=applicationContext.getBean(ReportService.class);

//		//获取配置中信息
//		String retentionDaysStr = applicationContext.getEnvironment().getProperty("log.retentionDays");
//		if (StringUtils.isNotEmpty(retentionDaysStr)) {
//			retentionDays = Integer.parseInt(retentionDaysStr);
//		}

    }

    public void stop() {
        while (process.isAlive()) {
            process.destroyForcibly();
        }
    }

    private void getPy() throws Exception{

        // 开始运行算法，修改任务状态，正在运行
        Task byId1 = taskService.getById(taskId);
        byId1.setTaskStatus(1);
        taskService.updateById(byId1);

        StringBuilder exe = new StringBuilder("C:/Users/KFS/anaconda3/envs/pytorch/python.exe ");
        exe.append(pyPath);

        logger.info("正在运行的python的脚本的命令行参数 ： " + exe);
        System.out.println();
        try {
            process = Runtime.getRuntime().exec(String.valueOf(exe));


            ThreadPoolUtil.threadPool.submit(() -> {
                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        System.out.println("out=[" + line + "]");
                    }
                } catch (Exception e) {
                    logger.error("======读取python算法输出流出错");
                }
            });

            ThreadPoolUtil.threadPool.submit(() -> {
                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        System.out.println("err=[" + line + "]");
                    }
                } catch (Exception e) {
                    logger.error("======读取python算法输出流出错");
                }
            });

            // waitFor方法会阻塞
            logger.info("{}算法结束 ===>  结果输出值:{}", pyPath, process.waitFor());

        } catch (Exception e) {
            e.printStackTrace();
            byId1.setTaskStatus(3);
            taskService.updateById(byId1);
        }
        if(taskService.getById(taskId).getTaskStatus()==1){
            byId1.setTaskStatus(3);
            taskService.updateById(byId1);
            return;
        }
        Task byId = taskService.getById(taskId);
        Integer id = byId.getPictureId();
        List<Maps> list = mapsService.list(new QueryWrapper<Maps>().lambda()
                .eq(Maps::getSampleId, id));
        List<MapsRes> list1 = mapsResService.list(new QueryWrapper<MapsRes>().lambda()
                .eq(MapsRes::getMapsId, list.get(0).getId()));

        if("predict.py".equals(pyPath)) {
            String path = list1.get(0).getPath();
            String suffix1 = path.substring(path.lastIndexOf("/"));
            String path1 = path.replace(suffix1, "") + "/ESB_files";
            File file = new File(path);
            File file1 = new File(path1);
            file.renameTo(file1);
            MapsRes mapsRes = list1.get(0);
            mapsRes.setPath(path1);
            mapsResService.updateById(mapsRes);
            List<Report> reports = reportService.list(new QueryWrapper<Report>().lambda()
                    .eq(Report::getPictureId, id)
                    .eq(Report::getType,1));
            Report report = reports.get(0);
            report.setResPath(report.getResPath().replace("SE2","ESB_files"));
            reportService.updateById(report);
            System.out.println("nb");
            String s = list.get(0).getPath().replace("/data/MAPS2/data/1478130726/SE2", "");
            String suffix = s.substring(s.lastIndexOf("/"));
            ZipUtil2.compressToZip(s, s.replace(suffix, ""), suffix + ".zip");
        }
        //TODO 修改任务状态
        byId1.setTaskStatus(2);
        taskService.updateById(byId1);
    }


    @Override
    public Void call() throws Exception {
        getPy();
        return null;
    }
}
